import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:stacked/stacked.dart';
import 'package:stacked_services/stacked_services.dart';
import 'package:vista/app/di/injection.dart';
import 'package:vista/app/router/app_router.dart';
import 'package:vista/features/inspiration/viewmodels/inspiration_detail_viewmodel.dart';
import 'package:vista/shared/services/auth_focus.dart';
import 'package:vista/shared/services/daily_inspiration_service.dart';
import 'package:vista/shared/services/relation_bond.dart';
import 'package:vista/shared/constants/color.dart';
import 'package:vista/shared/utils/flash_notifier.dart';
import 'package:vista/shared/utils/widget_extension.dart';
import 'package:vista/shared/widgets/auth_gate_modal.dart';
import 'package:vista/shared/widgets/complain_bottom_sheet.dart';

/// 每日灵感详情页面
class InspirationDetailView extends StatelessWidget {
  final String inspirationId;

  const InspirationDetailView({super.key, required this.inspirationId});

  @override
  Widget build(BuildContext context) {
    return ViewModelBuilder<InspirationDetailViewModel>.reactive(
      viewModelBuilder:
          () => InspirationDetailViewModel(
            getIt.get<AuthFocus>(),
            getIt.get<DailyInspirationService>(),
            getIt.get<RelationBond>(),
            inspirationId,
          )..initialize(),
      builder:
          (context, model, child) => Scaffold(
            body: Container(
              decoration: const BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/my-background.png'),
                  fit: BoxFit.fill,
                ),
              ),
              child: SafeArea(
                bottom: false,
                child: [
                  // 标题栏
                  _buildHeader(context, model),
                  // 可滚动内容
                  Expanded(
                    child: SingleChildScrollView(
                      child: [
                            // 灵感图片区域
                            _buildInspirationImageSection(context, model),
                            SizedBox(height: 14.h),
                            // 发布者信息和摄影参数
                            _buildAuthorAndParamsSection(context, model),
                            SizedBox(height: 100.h), // 底部留白
                          ]
                          .verticalShot(
                            crossAxisAlignment: CrossAxisAlignment.stretch,
                          )
                          .frameHorizontal(0),
                    ),
                  ),
                ].verticalShot(crossAxisAlignment: CrossAxisAlignment.stretch),
              ),
            ),
          ),
    );
  }

  /// 构建标题栏
  Widget _buildHeader(BuildContext context, InspirationDetailViewModel model) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.h),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Image.asset(
              'assets/images/back.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
          // 举报按钮
          GestureDetector(
            onTap: () async {
              await ComplainHelper.unveil(
                context,
                onComplain: (reason) {
                  FlashNotifier.flashSuccess('Report submitted successfully');
                  // 返回上一页
                  getIt.get<NavigationService>().back();
                },
              );
            },
            child: Image.asset(
              'assets/images/report.png',
              width: 24.w,
              height: 24.w,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建灵感图片区域
  Widget _buildInspirationImageSection(
    BuildContext context,
    InspirationDetailViewModel model,
  ) {
    if (model.inspiration == null) {
      return const SizedBox.shrink();
    }

    final inspiration = model.inspiration!;

    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 14.w),
      child: Stack(
        children: [
          // 主图片（宽高比347/622）
          AspectRatio(
            aspectRatio: 347 / 622,
            child: Hero(
              tag: 'inspiration_${inspiration.id}',
              child: Image.asset(
                inspiration.image,
                width: double.infinity,
                fit: BoxFit.cover,
              ),
            ),
          ),
          // inspiration-box.png 叠层（底部）
          Positioned(
            left: 0,
            right: 0,
            bottom: 0,
            child: Image.asset(
              'assets/images/inspiration-box.png',
              width: double.infinity,
              fit: BoxFit.fitWidth,
            ),
          ),
          // Container 叠层（标题、详情、小图、关注按钮）
          Positioned(
            left: 50.w,
            right: 50.w,
            bottom: 53.h,
            child: _buildInspirationOverlay(context, model),
          ),
        ],
      ),
    );
  }

  /// 构建灵感信息叠层
  Widget _buildInspirationOverlay(
    BuildContext context,
    InspirationDetailViewModel model,
  ) {
    if (model.inspiration == null) {
      return const SizedBox.shrink();
    }

    final inspiration = model.inspiration!;

    return ClipRRect(
      borderRadius: BorderRadius.circular(4.r),
      child: BackdropFilter(
        filter: ImageFilter.blur(sigmaX: 10, sigmaY: 10),
        child: Container(
          decoration: BoxDecoration(
            color: Colors.black.withValues(alpha: 0.05),
            borderRadius: BorderRadius.circular(4.r),
          ),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              // 小图
              Container(
                width: 36.w,
                height: 26.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4.r),
                  image: DecorationImage(
                    image: AssetImage(inspiration.image),
                    fit: BoxFit.cover,
                  ),
                ),
              ),
              SizedBox(width: 12.w),
              // 标题和详情
              Expanded(
                child: [
                  // 标题
                  Text(
                    inspiration.title,
                    style: TextStyle(
                      fontSize: 8.sp,
                      fontWeight: FontWeight.w700,
                      color: Colors.white,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 4.h),
                  // 详情
                  Text(
                    inspiration.description,
                    style: TextStyle(fontSize: 6.sp, color: Colors.white),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
              ),
              SizedBox(width: 12.w),
              // 关注按钮
              GestureDetector(
                onTap: () async {
                  if (model.currentUser == null) {
                    final result = await showDialog<bool>(
                      context: context,
                      builder: (context) => const AuthGateModal(),
                    );
                    if (result == true) {
                      // 跳转到登录页面
                      Navigator.of(context).pushNamed('/login');
                    }
                    return;
                  }

                  await model.toggleFollow();
                },
                child: Container(
                  padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.circular(44.r),
                  ),
                  child: Row(
                    mainAxisSize: MainAxisSize.min,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Icon(Icons.add, size: 10.w, color: Colors.black),
                      Text(
                        model.isFollowing ? 'Following' : 'Pay attention',
                        style: TextStyle(
                          fontSize: 6.sp,
                          color: Colors.black,
                          fontWeight: FontWeight.w600,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              SizedBox(width: 4.w),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建发布者信息和摄影参数区域
  Widget _buildAuthorAndParamsSection(
    BuildContext context,
    InspirationDetailViewModel model,
  ) {
    if (model.inspiration == null || model.author == null) {
      return const SizedBox.shrink();
    }

    final inspiration = model.inspiration!;
    final author = model.author!;
    final params = inspiration.photoParams;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 14.w),
      decoration: ShapeDecoration(
        color: const Color(0xFFFFA57F),
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 1.w),
          borderRadius: BorderRadius.circular(4),
        ),
        shadows: [
          BoxShadow(
            color: Color(0xFF000000),
            blurRadius: 0,
            offset: Offset(1, 1),
            spreadRadius: 0,
          ),
        ],
      ),
      child: [
        // 发布者信息
        _buildAuthorInfo(context, author),
        // 摄影参数
        _buildPhotoParams(context, params),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建发布者信息
  Widget _buildAuthorInfo(BuildContext context, author) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
      decoration: ShapeDecoration(
        color: Colors.white,
        shape: RoundedRectangleBorder(
          side: BorderSide(width: 1.w),
          borderRadius: BorderRadius.circular(4.r),
        ),
      ),
      child: Row(
        children: [
          // 用户头像
          GestureDetector(
            onTap: () async {
              // 检查是否是当前用户
              final currentUser = await getIt<AuthFocus>().getCurrentUser();
              if (currentUser != null && currentUser.id == author.id) {
                return; // 是自己的头像，不跳转
              }
              // 跳转到他人主页
              if (context.mounted) {
                await Navigator.of(context).pushNamed(
                  Routes.otherProfile,
                  arguments: {'userId': author.id},
                );
              }
            },
            child: CircleAvatar(
              radius: 24.r,
              backgroundColor: Colors.grey[200],
              backgroundImage:
                  author.avatar != null ? AssetImage(author.avatar!) : null,
              child:
                  author.avatar == null
                      ? Icon(Icons.person, size: 30.w, color: Colors.grey)
                      : null,
            ),
          ),
          SizedBox(width: 12.w),
          // 用户名和签名
          Expanded(
            child: [
              // 用户名
              Text(
                author.username,
                style: TextStyle(
                  fontSize: 20.sp,
                  fontWeight: FontWeight.w700,
                  color: Colors.black87,
                ),
              ),
              // 用户签名
              if (author.signature != null)
                Text(
                  '@ ${author.signature}',
                  style: TextStyle(
                    fontSize: 14.sp,
                    color: Colors.black87.withOpacity(0.7),
                  ),
                ),
            ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
          ),
          // 主页图标
          GestureDetector(
            onTap: () async {
              // 检查是否是当前用户
              final currentUser = await getIt<AuthFocus>().getCurrentUser();
              if (currentUser != null && currentUser.id == author.id) {
                return; // 是自己的头像，不跳转
              }
              // 跳转到他人主页
              if (context.mounted) {
                await Navigator.of(context).pushNamed(
                  Routes.otherProfile,
                  arguments: {'userId': author.id},
                );
              }
            },
            child: Container(
              width: 36.w,
              height: 36.w,
              decoration: BoxDecoration(
                color: ColorConstants.blueColor,
                borderRadius: BorderRadius.circular(4.r),
              ),
              child: Center(
                child: Icon(Icons.home, size: 18.w, color: Colors.white),
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建摄影参数
  Widget _buildPhotoParams(BuildContext context, params) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 10.h),
      child: [
        // 参数网格（两列）
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 左列
            Expanded(
              child: [
                _buildParamItem('Lens', params.lens),
                SizedBox(height: 8.h),
                _buildParamItem('FL', params.fl),
                SizedBox(height: 8.h),
                _buildParamItem('Flash', params.flash),
                SizedBox(height: 8.h),
                _buildParamItem('Exposure', params.exposure),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
            ),
            SizedBox(width: 16.w),
            // 右列
            Expanded(
              child: [
                _buildParamItem('Camera', params.camera),
                SizedBox(height: 8.h),
                _buildParamItem('ISO', params.iso),
                SizedBox(height: 8.h),
                _buildParamItem('Shutter', params.shutter),
                SizedBox(height: 8.h),
                _buildParamItem('Aperture', params.aperture),
              ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
            ),
          ],
        ),
      ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start),
    );
  }

  /// 构建单个参数项
  Widget _buildParamItem(String label, String value) {
    return [
      Text(label, style: TextStyle(fontSize: 12.sp, color: Colors.grey[600])),
      SizedBox(height: 2.h),
      Text(
        value,
        style: TextStyle(
          fontSize: 14.sp,
          fontWeight: FontWeight.w600,
          color: Colors.black87,
        ),
      ),
    ].verticalShot(crossAxisAlignment: CrossAxisAlignment.start);
  }
}
